// uhttp.js
import store from './store.js'

const config = {
	baseUrl: store.state.baseUrl,
	method: 'POST',
	dataType: 'json',
	showLoading: true,
	loadingText: '请稍等...',
	loadingTime: 800,
	originalData: true,
	loadingMask: true,
	header: {
		'content-type': 'application/json;charset=UTF-8'
	},
}

const install = (Vue, vm) => {
	Vue.prototype.$u.http.setConfig(config);

	// 请求拦截
	Vue.prototype.$u.http.interceptor.request = (config) => {
		let token = vm.$store.state.token
		if (token) {
			config.header.Authorization = 'Bearer ' + token
		} else {
			config.header.Authorization = ''
		}
		return config;
	}

	// 响应拦截
	Vue.prototype.$u.http.interceptor.response = (res) => {
		let code = res.data.code
		if (code == 0 || code >= 10000) {
			return res;
		} else if (code == 401) {
			vm.$u.route('/pages/user/login')
			return false;
		} else {
			vm.$msg('出了点小问题')
			return false;
		}
	}

	// 结束
}

export default {
	install
}
